<?php

/**
 * 抓取一个文章 信息
 */
namespace console\controllers;

use backend\models\NewsFlash;
use backend\models\NewsNom;
use common\models\User;
use Think\Exception;
use yii\console\Controller;


class NewsController extends Controller
{
    /**
     * 批处理脚本的实现
     * 一次取50
     */
    public function actionArticle()
    {
        $min = 0;
        $max = 2500;
        $batchnum = 50;
        $j = 0;
        for ($id = $min; $id <= $max + $batchnum; $id += $batchnum) {
            $url = [];
            for ($i = $id; $i < $id + $batchnum; $i++) {
                $url[] = 'http://v3.wufazhuce.com:8000/api/essay/' . $i;
            }
            $datas = static::multiRequest($url);
            file_put_contents("$id.one", $datas);
            foreach ($datas as $data) {
                $res = json_decode($data, true);
                if (isset($res['res']) && $res['res'] == 0) {
                    echo $j++ . "done" . PHP_EOL;
                    $ret = $res['data'];
                    $one = new Onearticle();
                    $one->content_id = $ret['content_id'];
                    $one->title = $ret['hp_title'];
                    $one->content = $ret['hp_content'];
                    $one->author = $ret['hp_author'];
                    $one->author_it = $ret['auth_it'];
                    $one->guide_word = $ret['guide_word'];
                    $one->wb_img_url = $ret['wb_img_url'];
                    $one->save(false);
                }
            }
        }
    }

    /**
     * @param $urls
     * @return array
     */
    public static function multiRequest($urls)
    {
        $mh = curl_multi_init();
        $curl_array = array();
        foreach ($urls as $i => $url) {
            $curl_array[$i] = curl_init($url);
            curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_array[$i], CURLOPT_URL, $url);
            curl_setopt($curl_array[$i], CURLOPT_HEADER, false);
            curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_array[$i], CURLOPT_SSL_VERIFYPEER, false);
            curl_multi_add_handle($mh, $curl_array[$i]);
        }
        $active = null;
        do {
            curl_multi_exec($mh, $active);
        } while ($active > 0);
        $response = [];
        foreach ($urls as $i => $url) {
            $response[$url] = curl_multi_getcontent($curl_array[$i]);
        }
        foreach ($urls as $i => $url) {
            curl_multi_remove_handle($mh, $curl_array[$i]);
        }
        curl_multi_close($mh);
        return $response;
    }

    public function singleCurl($url){
        $header = array(
            'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0',
            'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Content-Type:application/x-www-form-urlencoded;charset=utf-8'
        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    /**
     * 定时发送push，每次驻留时间最长为170秒,之后将退出，等待下一个脚本启动
     */
    public function actionCpublish(){
        set_time_limit(0);
        error_reporting(0);

        //查找未发送任务
        $waite_push = NewsFlash::find()->where(array('status' => NewsNom::NEWS_STATUS_WAT))
            ->orderBy(['ptime' => SORT_ASC])->asArray()->all();

        echo date("Y-m-d H:i:s",time())."\t"."Select tasks".PHP_EOL;
        if( !$waite_push ) {
            echo date("Y-m-d H:i:s",time())."\t"."No tasks".PHP_EOL;
            echo date("Y-m-d H:i:s",time())."\t"."waiting...".PHP_EOL;
            return false;
        }

        $second = 0;
        foreach ( $waite_push as $one ){
            $now = date("Y-m-d H:i:s",time());
            $publishtime = $one['ptime'];
            $dopush = false;

            echo date("Y-m-d H:i:s",time())."\t"."YII_ENV=".YII_ENV.PHP_EOL;
            echo date("Y-m-d H:i:s",time())."\t"."setpublishtime=".$publishtime.PHP_EOL;

            //当前未到发送时间，等待时间小于170秒，未触发push操作
            echo date("Y-m-d H:i:s",time())."\t"."loop second=";
            $minute = floor((strtotime($now)-strtotime($publishtime))%86400/60);
            while ( $minute <= 3 && $second <= 170 && $dopush == false ){
                echo $second." ";

                $now = date("Y-m-d H:i:s",time());
                if( $one['status'] == NewsNom::NEWS_STATUS_WAT && $publishtime && $now >= $publishtime ){

                    $publishone = NewsNom::findOne($one['id']);
                    echo "status=".$publishone->status." ".date("Y-m-d H:i:s",time()).PHP_EOL;

                    $split = date("Y-m-d H:i:s",strtotime("-4 minute"));
                    if( $publishone->status == NewsNom::NEWS_STATUS_WAT && $publishone->ptime >= $split  ){
                        NewsNom::updateAll(['status' => NewsNom::NEWS_STATUS_NOM],['id' => $one['id']]);
                    }else{
                        break;
                    }
                }

                sleep(1);
                $second += 1;
            }
            echo PHP_EOL;

            if( $second >= 170 ) {
                break;
            }
        }
    }

}
